package com.hamizhong.iflowers.web.action;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.hamizhong.iflowers.service.IGoodsService;
import com.hamizhong.iflowers.utils.MyConstants;
import com.hamizhong.iflowers.web.base.MyBaseAjaxAction;
import com.hamizhong.iflowers.web.dto.IOPResultDto;
import com.hamizhong.iflowers.web.vo.GoodsVO;
import com.hamizhong.iflowers.web.vo.IObjectVO;

public class AjaxInitShoppingCartListAction extends MyBaseAjaxAction {

	private IGoodsService iGoodsService = null;
	
	public IGoodsService getiGoodsService() {
		return iGoodsService;
	}
	public void setiGoodsService(IGoodsService iGoodsService) {
		this.iGoodsService = iGoodsService;
	}

	@Override
	protected JSONObject doRequest() {
		logger.info("...invoke...AjaxInitIndexGoodsAction...");
		HttpServletRequest request = getRQ();
		HttpServletResponse response = getRP();
		
		String cartGoodsStr = "";
		String newCartGoodsStr = "";
		String[] arr0;//长度为2，用于暂时存放key和value
		String[] arr1;//购物车中已经添加的个数（用“_”分隔）
		String[] arr2;//存放商品的key
		String[] arr3;//存放商品的数量
		//key和value之间通过“-”分隔
		
		JSONObject jo = new JSONObject();
		JSONArray ja = new JSONArray();
		JSONObject jobj;
		
		GoodsVO goodsVO = null;
		
		try {
			Cookie[] cookie = request.getCookies();
			if(cookie != null) {
				for(int i=0;i<cookie.length;i++) {
					String res = cookie[i].getName();
					if(res.equals("iFlowers_Shopping_Cart")) {
						cartGoodsStr = cookie[i].getValue();
						break;
					}
				}
			}
			if(cartGoodsStr != "") {
				arr1 = cartGoodsStr.split("_");
				arr2 = new String[arr1.length];
				arr3 = new String[arr1.length];

				for(int i=0;i<arr1.length;i++) {
					arr0 = new String[2];
					arr0 = arr1[i].split("-");
					arr2[i] = arr0[0];
					arr3[i] = arr0[1];
				}
				for(int i=0;i<arr2.length;i++) {
					goodsVO = new GoodsVO();
					IOPResultDto<IObjectVO> dto = iGoodsService.findById(Integer.valueOf(arr2[i]));
					goodsVO = dto.getFirstResult().getGoodsVOList().get(0);
					jobj = new JSONObject();
					jobj.put("goodsId", goodsVO.getGoodsId());
					jobj.put("goodsName", goodsVO.getGoodsName());
					jobj.put("goodsPrice", goodsVO.getGoodsPrice());
					jobj.put("goodsCnt", Integer.valueOf(arr3[i]));
					jobj.put("goodsPictureS", goodsVO.getGoodsPictureS());
					ja.add(jobj);
				}
				jo.put("data", ja.toString());
			}else {
				jo.put("data", "");
			}
			jo.put("result", MyConstants.AJAX_SUCCESS);
			return jo;
		} catch (Exception e) {
			e.printStackTrace();
			jo.put("result", MyConstants.AJAX_FAILED_ALERT);
			return jo;
		}
	}

}
